const path = require('path');
const fs = require('fs');
const childProcess = require('child_process');
const chalk = require('chalk');
const inquirer = require('inquirer');
const ora = require('ora');

const releaseUrl = 'npm publish --registry http://nexus.saas.hand-china.com/content/repositories/hzero-ui/';
const packages = fs.readdirSync(path.resolve(__dirname, '../packages'));
const spinner = new ora();

inquirer
.prompt([
  {
    type: 'list',
    name: 'modules',
    message: 'Please select the module to release ？',
    choices: ['all', ...packages],
  }
])
.then(answers => {
  if (answers.modules === 'all') {
    spinner.text = `${chalk.yellow('all module release...')}`;
    spinner.color = 'yellow';
    packages.some((item) => {
      spinner.start();
      childProcess.exec(`cd ${path.resolve(__dirname, `../packages/${item}`)}; yarn transpile; ${releaseUrl};`, (error, stdout) => {
        if (error) {
          console.log(`\n ${error}`);
          spinner.fail(`${chalk.red(`${item} release failed !!!`)} release stop.`);
          return true;
        }
        spinner.color = 'green';
        spinner.text = `${chalk.green(` ${item} release success.`)}`;
        spinner.succeed();
      });
    })
  } else {
    spinner.start();
    spinner.text = `${chalk.yellow(`${answers.modules} release...`)}`;
    spinner.color = 'yellow';
    childProcess.exec(`cd ${path.resolve(__dirname, `../packages/${answers.modules}`)}; yarn transpile; ${releaseUrl};`, (error, stdout) => {
      if (error) {
        console.log(`\n ${error}`);
        spinner.fail(`${chalk.red(`${answers.modules} release failed !!!`)}`);
        return;
      }
      spinner.color = 'green';
      spinner.text = `${chalk.green(` ${answers.modules} release success.`)}`;
      console.log('success');
      spinner.succeed();
    });
  }
});
